//-----------------------------------------------------------------------
// <copyright company="Olson Software Limited">
//      (c) Copyright Olson Software Limited.
//      This source is subject to the Microsoft Public License (Ms-PL).
//      Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
//      All other rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Principal;

namespace Insight.Library.Navigation
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public sealed class RequiresRolesAttribute : AuthorizationAttribute
    {
        public ReadOnlyCollection<string> Roles { get; private set; }

        public RequiresRolesAttribute(string role)
        {
            if (string.IsNullOrEmpty(role))
            {
                throw new ArgumentNullException("role");
            }
            Roles = new List<string> { role }.AsReadOnly();
        }

        public RequiresRolesAttribute(params string[] roles)
        {
            if (roles == null)
            {
                throw new ArgumentNullException("roles");
            }
            if (roles.Length == 0)
            {
                throw new ArgumentException("must have one or more roles");
            }
            Roles = roles.ToList().AsReadOnly();
        }

        public override bool Authorize(IPrincipal principal)
        {
            if (!principal.Identity.IsAuthenticated)
            {
                return false;
            }
            foreach (string str in Roles)
            {
                if (!principal.IsInRole(str))
                {
                    return false;
                }
            }
            return true;
        }

        
    }
}